package com.runen.wnhz.runen.ui.fragment.publicm;

import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.data.entity.BaseEntity;
import com.runen.wnhz.runen.data.entity.FragmentInfo;
import com.runen.wnhz.runen.data.entity.ShopInfo;
import com.runen.wnhz.runen.data.entity.ShopListEntity;
import com.runen.wnhz.runen.data.entity.ShopTypeEntity;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.di.component.DaggerPublicmComponent;
import com.runen.wnhz.runen.di.module.PublicmModule;
import com.runen.wnhz.runen.presenter.Contart.PublicmContart;
import com.runen.wnhz.runen.presenter.iPresenter.IPublicmPresenter;
import com.runen.wnhz.runen.ui.adapter.puadapter.ViewPagerAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.OnClick;

/**
 * Created by Administrator on 2018-04-08.
 * 数据服务界面
 */

public class PublicFragment extends BaseFragment<IPublicmPresenter> implements PublicmContart.View {

    public static final String TAG = "PublicFragment";
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;
    private RelativeLayout rlSelectTime;
    private LinearLayout flTimeselectContainer;
    TimePickerView pvCustomTime;
    private TextView tvTimeStart;
    private TextView tvTimeEnd;
    UserBean reqeustUser;
    //当前页面选中页
    int currentPage = 0;
    String currentShopTypeId;
    //起始时间
    String sDate = "2018-03-26";
    String eDate = "2018-04-26";
    //分页page
    int pageNum = 0;
    //类型店铺名集合
    List<ShopTypeEntity> mlist = new ArrayList<>();
    //类型店铺集合
    BaseEntity<List<ShopTypeEntity>> listBaseEntity;
    private List<FragmentInfo> mDatas = new ArrayList<>();

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {
        DaggerPublicmComponent.builder().applicationComponent(appComponent)
                .publicmModule(new PublicmModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.public_fragment_layout;
    }

    @Override
    public void initUiAndListener(View view) {
        tabLayout = view.findViewById(R.id.public_tablayout);
        viewPager = view.findViewById(R.id.public_viewpager);
        rlSelectTime = view.findViewById(R.id.rl_select_time);
        flTimeselectContainer = view.findViewById(R.id.fl_timeselect_container);
        tvTimeStart = view.findViewById(R.id.tv_start);
        tvTimeEnd = view.findViewById(R.id.tv_end);
        //设置viewpager 加载东西
        initSetAdapter();
        setViewPagerListener();
        //初始化时间选择器
        pvCustomTime = getTimePickerView();

    }

    //设置viewpager滑动监听
    private void setViewPagerListener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                mPresenter.getShopList();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void init() {
        reqeustUser = ACacheUtlis.getInstance().getReqeustUser(getActivity());
//        Log.d("token", getToken());
        //获取店铺类型
        mPresenter.getShoptype();
        //获取店铺列表
        mPresenter.getShopList();
    }

    List<Fragment> fragments = new ArrayList<>();

    private void initSetAdapter() {
//       
//        mlist.add("美食类");
//        mlist.add("书籍类");
//        mlist.add("服装美容类");
//        mlist.add("小家电类");
//        mlist.add("居家类");
//        mlist.add("其他");
        for (int i = 0; i < mlist.size(); i++) {
            AllFragment fragment = AllFragment.newInstance(mlist.get(i).getName(), currentShopTypeId);
            fragments.add(fragment);
        }
        viewPagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager(), mlist, fragments);
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }


    @OnClick({R.id.rl_select_time})
    public void timeSelect(View view) {
        switch (view.getId()) {
            case R.id.rl_select_time:
                //弹出时间选择界面选择时间，点击确认后赋值给
                if (null != pvCustomTime)
                    pvCustomTime.show();
                break;
        }
    }

    int mCurrentType = 0;
    TextView timeType;

    private TimePickerView getTimePickerView() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        return new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (mCurrentType) {
                    case 0:
                        tvTimeStart.setText(getTime(date));
                        timeType.setText("结束时间");
                        break;
                    case 1:
                        tvTimeEnd.setText(getTime(date));
                        timeType.setText("开始时间");
                        break;
                }
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_time_select, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        timeType = v.findViewById(R.id.tv_time);
                        final TextView tv_confir = v.findViewById(R.id.tv_confir);
                        tv_confir.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                TextView timeConfir = view.findViewById(R.id.tv_confir);
                                timeConfir.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Log.d("mCurrentType:", mCurrentType + "");
                                        pvCustomTime.returnData();
                                        mCurrentType++;
                                        if (mCurrentType == 2) {
                                            mCurrentType = 0;
                                            pvCustomTime.dismiss();
                                            return;
                                        }
                                    }
                                });
                            }
                        });
                    }
                })
                .setDecorView(flTimeselectContainer)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDividerColor(Color.DKGRAY)
                .setContentTextSize(20)
                .setOutSideCancelable(true)
                .setBackgroundId(0x00000000)
                .isDialog(false)
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        return format.format(date);
    }

    @Subscriber(tag = "shopType")
    public void selectTab(String id) {
        tabLayout.getTabAt(Integer.valueOf(id) - 1).select();
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setMiddleTitleText("数据服务");
        mTitleBuilder.setMiddleTitleTextColor(getResources().getColor(R.color.white));
    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {

    }

    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }

    @Override
    public String getToken() {
        if(reqeustUser == null){
            return null;
        }else {
            return reqeustUser.getToken();
        }
    }

    /**
     * 更新导航栏店铺类型
     *
     * @param listBaseEntity
     */
    @Override
    public void saveShopeTypeList(BaseEntity<List<ShopTypeEntity>> listBaseEntity) {
        this.listBaseEntity = listBaseEntity;
        for (int i = 0; i < listBaseEntity.getData().size(); i++) {
            mlist.add(listBaseEntity.getData().get(i));
        }
        Log.d("mlist.size", mlist.size() + "");
        if (viewPagerAdapter != null) {
            viewPagerAdapter = null;
        }
        initSetAdapter();
    }

    /**
     * 更新店铺列表
     *
     * @param baseEntity
     */
    List<ShopInfo> shopInfoList = new ArrayList<>();

    @Override
    public void updateShopList(BaseEntity<ShopListEntity<List<ShopInfo>>> baseEntity) {
        Log.d("PublicFragment", baseEntity.toString());
        if (shopInfoList != null) {
            shopInfoList.clear();
        }
        for (ShopInfo shopInfo :
                baseEntity.getData().getList()) {
            shopInfoList.add(shopInfo);
        }
        Log.d("PublicFragment", shopInfoList.toString());
        currentShopTypeId = listBaseEntity.getData().get(currentPage).getId();
        viewPagerAdapter.update(currentPage, shopInfoList, currentShopTypeId, sDate, eDate, pageNum + "");
        Log.d("PublicFragment", shopInfoList.toString());
    }

    @Override
    public String getTypeId() {
        if (listBaseEntity != null) {
            currentShopTypeId = listBaseEntity.getData().get(currentPage).getId();
            Log.d("pub-currentShopTypeId", currentShopTypeId);
            return currentShopTypeId;
        }
        return 1 + "";
    }

    @Override
    public String getSdate() {
        return "2018-03-26";
    }

    @Override
    public String getEdate() {
        return "2018-05-31";
    }

    @Override
    public String getpageNum() {
        return 0 + "";
    }

    @Override
    public String getShopId() {
        return null;
    }
}
